package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ITravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

/**
 * @author hslef
 */
@Service
public class TravelCommentImpl implements ITravelCommentService {
    @Autowired
    private ITravelCommentRepository commentRepository;

    @Autowired
    private MongoTemplate template;

    @Override
    public TravelComment addComment(TravelComment comment) {
        comment.setCreateTime(new Date());
        if(comment.getType() == 1){
            TravelComment refComment = commentRepository.findById(comment.getRefComment().getId()).get();
            comment.setRefComment(refComment);
        }
        commentRepository.save(comment);
        return comment;
    }

    @Override
    public Page<TravelComment> query(TravelCommentQuery qo) {
        Query query = new Query();
        if (qo.getTravelId() != null) {
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }
        long count = template.count(query, TravelComment.class);
        if (count > 0) {
            Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1,
                    qo.getPageSize(),
                    Sort.by(Sort.Direction.DESC,"createTime")
            );
            query.with(pageable);
            List<TravelComment> travelComments =  template.find(query, TravelComment.class);
            return new PageImpl<>(travelComments,pageable,count);
        }
        return Page.empty();
    }

    @Override
    public List<TravelComment> getCommentByUserId(Long uid) {
        Query query = new Query();
        //封装查询条件
        Criteria criteria = Criteria.where("userId").is(uid);
        query.addCriteria(criteria);
        List<TravelComment> travelComments = template.find(query, TravelComment.class);

        return travelComments;
    }
}
